//
//  NewFeatureView.swift
//  LEOweibo
//
//  Created by zz on 16/3/6.
//  Copyright © 2016年 zz. All rights reserved.
//

import UIKit
private let LEONewFeatureImageCount = 4
class NewFeatureView: UIView {
    
    //MARK:- 构造函数
    override init(frame: CGRect) {
        super.init(frame: UIScreen.mainScreen().bounds)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK:- 私有控件
    private var pageControl = UIPageControl()
}
//MARK:- 设置界面
extension NewFeatureView {
    
    private func setupUI() {
        
        let scrollView  = UIScrollView(frame: bounds)
        addSubview(scrollView)
        addSubview(pageControl)
        scrollView.contentSize = CGSize(width: bounds.size.width * CGFloat(LEONewFeatureImageCount+1), height: 0)
        for  i in 0..<LEONewFeatureImageCount{
            let pic = UIImageView(leoImage: "new_feature_\(i+1)")
            scrollView.addSubview(pic)
            pic.frame = CGRectOffset(bounds, CGFloat(i)*bounds.width, 0)
        }
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.pagingEnabled = true
        scrollView.bounces = false
        ///分页控件自动布局
        pageControl.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.bottom.equalTo(self).offset(-80)
        }
        pageControl.currentPage = 0
        pageControl.numberOfPages = LEONewFeatureImageCount
        pageControl.currentPageIndicatorTintColor = UIColor.orangeColor()
        pageControl.pageIndicatorTintColor = UIColor.darkGrayColor()
        //设置滚动视图的代理
        scrollView.delegate = self
    }
}

//MARK:- UIScrollViewDelegate
extension NewFeatureView: UIScrollViewDelegate {
    //开始滚动的时候调用
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        let offset = scrollView.contentOffset.x / bounds.width
        pageControl.currentPage = Int(offset + 0.5)
        
        if Int(offset+0.5) == LEONewFeatureImageCount{
            pageControl.hidden = true
        }
    }
    //开始减速滚动的时候调用
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        let page = Int(scrollView.contentOffset.x / bounds.width)
        
        if page == LEONewFeatureImageCount{
            removeFromSuperview()
        }
    }
    
}

